package com.example.cameraapp.activity;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.Face;
import android.hardware.camera2.params.MeteringRectangle;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.AudioManager;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaActionSound;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.SystemClock;
import android.util.Log;
import android.util.Size;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Chronometer;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.viewpager.widget.ViewPager;

import com.example.cameraapp.R;
import com.example.cameraapp.fragment.MyMenuFragmentAdapter;
import com.example.cameraapp.util.BitmapUtil;
import com.example.cameraapp.util.GetBitmap;
import com.example.cameraapp.util.LogUtil;
import com.example.cameraapp.view.FaceView;
import com.example.cameraapp.wbstrategy.AutoWBStrategy;
import com.example.cameraapp.wbstrategy.DaylightWBStrategy;
import com.example.cameraapp.wbstrategy.FlashStrategy;
import com.example.cameraapp.wbstrategy.FluoreWBStrategy;
import com.example.cameraapp.wbstrategy.IncandeWBStrategy;
import com.example.cameraapp.wbstrategy.ShadeWBStrategy;
import com.example.cameraapp.wbstrategy.TwilightWBStrategy;
import com.example.cameraapp.wbstrategy.WarmWBStrategy;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SunCameraActivity extends AppCompatActivity implements View.OnClickListener,View.OnTouchListener{

    private long firstTime = 0;
    private int textureWidth;
    private int textureHeight;
    private int speedShutMod = 0;
    private int faceCount = 0;
    private float mZoomValue;
    private float oldDist;
    private boolean isRecording;
    private String rootPath;
    private String cameraId;
    private String touchMode;
    private ImageButton takePhotoButton;
    private ImageButton rotateButton;
    private ImageButton btn_flash;
    private TextureView texturePreview;
    private TextView zoomNumber;
    private TextView burstNumber;
    private TextView delayNumber;
    private List<TextView> tagViews;
    private ImageView albumImage;
    private ImageView dark_screen;
    private ImageView image_focus;
    private Image captureImage;
    private ImageReader imageReader;
    private CameraManager cameraManager;
    private CameraCharacteristics cameraCharacteristics;
    private CameraDevice cameraDevice;
    private HandlerThread handlerThread;
    private Handler mBackgroundHandler;
    private CaptureRequest.Builder previewBuilder;
    private CaptureRequest.Builder captureBuilder;
    private CameraCaptureSession previewSession;
    private Integer menuVisible = 0;
    private ImageButton menuButton;
    private ViewPager viewPager;
    private LinearLayout parentLayout;
    private ConstraintLayout bottomConstraint;
    private ConstraintLayout previewConstraint;
    private SurfaceTexture surfaceTexture;
    private Surface previewSurface;
    private Surface mediaRecorderSurface;
    private CameraCaptureSession.CaptureCallback previewCallBack;
    private MediaActionSound mediaActionSound;
    private final SeekBar.OnSeekBarChangeListener seekListener;
    private final SeekBar.OnSeekBarChangeListener balanceListener;

    private final View.OnClickListener tagListener;
    private final View.OnClickListener flashListener;
    /*private final View.OnClickListener facehListener;
    private final View.OnClickListener delayListener;*/

    private final ImageReader.OnImageAvailableListener imageReaderListener;

    private Size optimalSize;
    private MediaRecorder recorder;
    private HashMap<Long, Bitmap> burstMap;
    private File videoFile;
    private Rect newRect;
    private List<RectF> faceList;

    private SharedPreferences share;

    private SeekBar zoomSeekBar;
    private SeekBar balanceSeekBar;

    private int delayTime = 0;
    private Long nowTimer = 0L;
    private Long oldTimer = 0L;
    private Long touchDown = 0L;
    private Long touchUp = 0L;

    //录像
    private ImageButton MedioIcon;
    private Chronometer chronometer;

    //绘制人脸
    private Size cPixelSize;
    private int[] faceDetectModes;
    private FaceView faceView;
    private MediaPlayer mediaPlayer;
    private AudioManager audioManager;

    //模式切换按钮
    private ImageButton faceButton;
    private ImageButton delayButton;
    private TextView textView_face;
    private TextView textView_delay;
    private TextView textView_balance;

    private ImageView autoWB,cloudyWB,daylightWB,fluoreWB,incandeWB,shadeWB,twilightWB,warmWB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        parentLayout = (LinearLayout) inflater.inflate(R.layout.activity_sun_camera, null);
        setContentView(parentLayout);
        share = Objects.requireNonNull(this).getSharedPreferences("delayTime", Context.MODE_PRIVATE);

        startBackgroundThread(); //开启一个后台线程

        initEvent(); //初始化事件

        initCameraManager("0");    //初始化CameraManager

        initTextureView();  //初始化TextureView

        setWindowFlag(); //设置顶部状态栏
        showFaceNumber();
    }

    //开启一个后台线程
    private void startBackgroundThread() {
        handlerThread = new HandlerThread("CameraThread");
        handlerThread.start();
        mBackgroundHandler = new Handler(handlerThread.getLooper());
    }

    //初始化事件
    public void initEvent() {
        tagViews = new ArrayList<>();
        burstMap = new HashMap<>();
        MyMenuFragmentAdapter adapter = new MyMenuFragmentAdapter(getSupportFragmentManager());
        viewPager = parentLayout.findViewById(R.id.viewPaper_layout);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);
        //viewPager.setAlpha(0.8F);

        takePhotoButton = parentLayout.findViewById(R.id.btn_simple_takePhoto);
        rotateButton = parentLayout.findViewById(R.id.btn_simple_rotate);
        albumImage = parentLayout.findViewById(R.id.btn_simple_album);

        image_focus = parentLayout.findViewById(R.id.image_focus);
        texturePreview = parentLayout.findViewById(R.id.simple_texture_preview);
        bottomConstraint = parentLayout.findViewById(R.id.simple_bottom_constraintLayout);
        previewConstraint = parentLayout.findViewById(R.id.constraint_preview);
        zoomNumber = parentLayout.findViewById(R.id.text_zoom_number);
        burstNumber = parentLayout.findViewById(R.id.text_burst_number);
        delayNumber = parentLayout.findViewById(R.id.text_delay_number);
        dark_screen = parentLayout.findViewById(R.id.dark_screen);
        tagViews.add((TextView) parentLayout.findViewById(R.id.choice_balance));
        tagViews.add((TextView) parentLayout.findViewById(R.id.choice_takePhoto));
        tagViews.add((TextView) parentLayout.findViewById(R.id.choice_takeVideo));
        for (final TextView tagView : tagViews) {
            tagView.setOnClickListener(tagListener);
        }

        MedioIcon = findViewById(R.id.btn_time);
        MedioIcon.setOnClickListener(this);

        btn_flash = parentLayout.findViewById(R.id.btn_flash);
        btn_flash.setOnClickListener(flashListener);



        faceButton = parentLayout.findViewById(R.id.menu_option_2);
        faceButton.setOnClickListener(this);
        textView_face = findViewById(R.id.menu_text_2);
        textView_face.setText("关闭");

        delayButton = parentLayout.findViewById(R.id.menu_option_1);
        delayButton.setOnClickListener(this);
        textView_delay = findViewById(R.id.menu_text_1);
        textView_delay.setText("无延时");

       /* textView_balance = findViewById(R.id.choice_balance);
        textView_balance.setOnClickListener(this);*/

        parentLayout.findViewById(R.id.btn_zoom).setOnClickListener(this);
        zoomSeekBar = parentLayout.findViewById(R.id.zoom_seekBar);
        zoomSeekBar.setOnSeekBarChangeListener(seekListener);

        balanceSeekBar = parentLayout.findViewById(R.id.sb_awb);
        balanceSeekBar.setOnSeekBarChangeListener(balanceListener);


        texturePreview.setOnTouchListener(this);
        //menuButton.setOnClickListener(this);
        //takePhotoButton.setOnTouchListener(this);
        takePhotoButton.setOnClickListener(this);
        rotateButton.setOnClickListener(this);
        albumImage.setOnClickListener(this);
        rootPath = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM)), "CameraTestStorage").toString() + "/";
        mediaActionSound = new MediaActionSound();
        new GetLatestAlbum().run();
        touchMode = "Single";
        mZoomValue = 0f;
        isRecording = false;

        //录像计时器
        chronometer = (Chronometer)findViewById(R.id.chronometer);

        //人脸识别
        faceView = new FaceView(this);
        faceList = new ArrayList<>();
        previewConstraint.addView(faceView);


        //白平衡
        autoWB = findViewById(R.id.wb_auto);
        autoWB.setOnClickListener(this);

        cloudyWB = findViewById(R.id.wb_cloudy);
        cloudyWB.setOnClickListener(this);

        daylightWB = findViewById(R.id.wb_daylight);
        daylightWB.setOnClickListener(this);

        fluoreWB = findViewById(R.id.wb_fluore);
        fluoreWB.setOnClickListener(this);

        incandeWB = findViewById(R.id.wb_incande);
        incandeWB.setOnClickListener(this);

        shadeWB = findViewById(R.id.wb_shade);
        shadeWB.setOnClickListener(this);

        twilightWB = findViewById(R.id.wb_twilight);
        twilightWB.setOnClickListener(this);

        warmWB = findViewById(R.id.wb_warm);
        warmWB.setOnClickListener(this);


        int time = share.getInt("delayTime", 0);
        changeDelayMode(time);
    }

    //tags事件监听
    {
        tagListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (((TextView) v).getCurrentTextColor() !=
                        SunCameraActivity.this.getResources().getColor(R.color.blue)) {
                    for (TextView view : tagViews) {
                        if (view.getId() != v.getId()) {
                            view.setTextColor(SunCameraActivity.this.getResources().getColor(R.color.white));
                        } else {
                            view.setTextColor(SunCameraActivity.this.getResources().getColor(R.color.blue));
                        }
                    }
                    if (v.getId() == tagViews.get(0).getId()) {  //白平衡
                        takePhotoButton.setId(R.id.btn_simple_balance);
                        takePhotoButton.setOnClickListener(SunCameraActivity.this);
                        takePhotoButton.setImageResource(R.drawable.icon_recorder_red);
                        Log.e("TAG","点击了白平衡");
                        if (balanceSeekBar.getVisibility() == View.GONE) {
                            balanceSeekBar.setVisibility(View.VISIBLE); //显示缩放条
                            autoWB.setVisibility(View.VISIBLE);
                            cloudyWB.setVisibility(View.VISIBLE);
                            daylightWB.setVisibility(View.VISIBLE);
                            fluoreWB.setVisibility(View.VISIBLE);
                            incandeWB.setVisibility(View.VISIBLE);
                            shadeWB.setVisibility(View.VISIBLE);
                            twilightWB.setVisibility(View.VISIBLE);
                            warmWB.setVisibility(View.VISIBLE);

                        }
                    } else if (v.getId() == tagViews.get(1).getId()) {  //拍照
                        takePhotoButton.setId(R.id.btn_simple_takePhoto);
                        takePhotoButton.setOnClickListener(SunCameraActivity.this);
                        takePhotoButton.setImageResource(R.drawable.icon_recorder_white);
                        chronometer.setVisibility(View.GONE);  //不显示定时器
                        MedioIcon.setVisibility(View.GONE);  //不显示录像图标
                        balanceSeekBar.setVisibility(View.GONE); //不显示
                        autoWB.setVisibility(View.GONE);
                        cloudyWB.setVisibility(View.GONE);
                        daylightWB.setVisibility(View.GONE);
                        fluoreWB.setVisibility(View.GONE);
                        incandeWB.setVisibility(View.GONE);
                        shadeWB.setVisibility(View.GONE);
                        twilightWB.setVisibility(View.GONE);
                        warmWB.setVisibility(View.GONE);
                    } else if (v.getId() == tagViews.get(2).getId()) { //录像
                        takePhotoButton.setId(R.id.btn_simple_record);
                        takePhotoButton.setOnClickListener(SunCameraActivity.this);
                        takePhotoButton.setImageResource(R.drawable.icon_recorder_red);
                        balanceSeekBar.setVisibility(View.GONE); //不显示
                        autoWB.setVisibility(View.GONE);
                        cloudyWB.setVisibility(View.GONE);
                        daylightWB.setVisibility(View.GONE);
                        fluoreWB.setVisibility(View.GONE);
                        incandeWB.setVisibility(View.GONE);
                        shadeWB.setVisibility(View.GONE);
                        twilightWB.setVisibility(View.GONE);
                        warmWB.setVisibility(View.GONE);
                    }
                } else say("按兵不动");
            }
        };
    }

    //seekBar事件监听
    {
        seekListener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                mZoomValue = (float) (progress * 0.01);
                applyZoom(mZoomValue);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        };
    }

    //balanceListener事件监听
    {
        balanceListener = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        };
    }

    //  闪光灯事件监听
    {
        flashListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (previewBuilder.get(CaptureRequest.FLASH_MODE).equals(CaptureRequest.FLASH_MODE_OFF)) {
                    previewBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON);
                    previewBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH);

                    try {
                        previewSession.setRepeatingRequest(previewBuilder.build(), previewCallBack, mBackgroundHandler);
                        btn_flash.setBackground(SunCameraActivity.this.getResources().getDrawable(R.drawable.icon_shangguangdengoff));
                        say("闪光灯开启");
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                } else {
                    previewBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);
                    try {
                        previewSession.setRepeatingRequest(previewBuilder.build(), previewCallBack, mBackgroundHandler);
                        btn_flash.setBackground(SunCameraActivity.this.getResources().getDrawable(R.drawable.icon_shanguangdeng));
                        say("闪光灯关闭");
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
    }

    //imageReader事件监听
    {
        //  拍照回传数据
        imageReaderListener = new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(final ImageReader reader) {
                captureImage = reader.acquireNextImage();
            }
        };
    }

    FlashStrategy wb;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_simple_takePhoto:
                Log.e("TAG","点击了拍照按钮");
                takePhoto();
                photo_voice();   //添加拍照的声音
                break;
            case R.id.btn_simple_takeDelay:
                final int shareDelayTime = share.getInt("delayTime", 0);
                if (delayTime != shareDelayTime) {
                    Log.e("TAG","倒计时过程中点击了拍照按钮");
                    delayTime = -1;
                    takePhoto();
                } else {
                    takeDelayShot();
                }
                break;
            case R.id.btn_simple_record:
                Log.e("TAG","点击了录像按钮");
                //takePhotoButton.setClickable(false);
                takeVideo();
                video_voice();  //添加录像的声音
                break;
            case R.id.btn_simple_rotate:
                rotateCamera();
                break;
            case R.id.btn_simple_album:
                Intent intent = new Intent(this, AlbumActivity.class)
                        .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
            case R.id.menu_option_1:
                int time = 0;
                if (textView_delay.getText().equals("无延时")) {
                    time = 3;
                } else if (textView_delay.getText().equals("3秒延时")) {
                    time = 5;
                } else if (textView_delay.getText().equals("5秒延时")) {
                    time = 10;
                }
                SharedPreferences.Editor edit = share.edit();
                edit.putInt("delayTime", time);
                edit.apply();
                changeDelayMode(time);
                break;
            case R.id.menu_option_2:
                Log.e("TAG","点击了人脸识别");
                changeFaceDetectedMode((share.getInt("faceMode", 0) == 0) ? 1 : 0);
                break;
            case R.id.btn_zoom:
                if (zoomSeekBar.getVisibility() == View.GONE) {
                    zoomSeekBar.setVisibility(View.VISIBLE); //缩放条
                    zoomNumber.setVisibility(View.VISIBLE);  //缩放数值
                } else if (zoomSeekBar.getVisibility() == View.VISIBLE) {
                    zoomSeekBar.setVisibility(View.GONE);
                    zoomNumber.setVisibility(View.GONE);
                }
                break;
            case R.id.btn_simple_balance:
                takePhoto();
                photo_voice();   //添加拍照的声音
                Log.e("TAG","点击了白平衡按钮并拍照成功！");
                break;
            case R.id.wb_cloudy:
                wb = new AutoWBStrategy();
                break;
            case R.id.wb_daylight:
                wb = new DaylightWBStrategy();
                break;
            case R.id.wb_fluore:
                wb = new FluoreWBStrategy();
                break;
            case R.id.wb_incande:
                wb = new IncandeWBStrategy();
                break;
            case R.id.wb_shade:
                wb = new ShadeWBStrategy();
                break;
            case  R.id.wb_twilight:
                wb = new TwilightWBStrategy();
                break;
            case R.id.wb_warm:
                wb = new WarmWBStrategy();
                break;
        }
        if (wb != null){
            wb.setCaptureRequest(previewBuilder,previewSession,mBackgroundHandler);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.simple_texture_preview) {
            //  单指抬起
            if (event.getAction() == MotionEvent.ACTION_UP) {
                //  双指移动后的抬起不做任何操作
                if (touchMode.equals("Double")) {
                    touchMode = "Single";
                } else {
                    //  单指抬起关闭隐藏各个阻挡屏幕的组件
                    zoomSeekBar.setVisibility(View.GONE);
                    zoomNumber.setVisibility(View.GONE);
                    Point point = new Point((int) event.getX(), (int) event.getY());
                    new Focus(point).run();
                    startControlAFRequest(calcTapAreaForCamera2(cameraCharacteristics, point.x, point.y, 10, 2));
                }
            }
            //  双指按下
            else if (event.getAction() == 261) {
                touchMode = "Double";
                oldDist = distance(event);
                zoomSeekBar.setVisibility(View.VISIBLE);
                zoomNumber.setVisibility(View.VISIBLE);
            }
            //  双指移动
            else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                if (touchMode.equals("Double")) {
                    // 两个手指滑动
                    float newDist = distance(event);
                    //  小于最大值1.0
                    if (mZoomValue <= 1.0F) {
                        //  大于最小值0
                        mZoomValue = Math.max((float) (mZoomValue + (newDist - oldDist) * 0.00005), 0);
                    } else mZoomValue = 1.0F;
                    zoomSeekBar.setProgress((int) (mZoomValue * 100));
                    say("mZoomValue = " + mZoomValue);
                    applyZoom(mZoomValue);
                }
            }
        }
        return true;
    }

    //初始化CameraManager
    public void initCameraManager(String id) {
        cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        cameraId = id;
        try {
            cameraCharacteristics = cameraManager.getCameraCharacteristics(cameraId);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    //激活延时拍照
    public void activeDelayMode(int time) {
        if (time != 0) {
            takePhotoButton.setId(R.id.btn_simple_takeDelay);
            delayTime = time;
            Toast.makeText(this, "延迟" + time + "秒拍照", Toast.LENGTH_SHORT).show();
        } else {
            takePhotoButton.setId(R.id.btn_simple_takePhoto);
        }
    }

    //开个线程来加载最新图片
    public class GetLatestAlbum implements Runnable {

        @Override
        public void run() {
            getLatestAlbum();
        }

        //    获取本软件自定义目录下最新的照片
        private void getLatestAlbum() {
            File albumDirectory = new File(rootPath);
            if (albumDirectory.isDirectory() || albumDirectory.mkdir()) {
                List<String> fileList = new ArrayList<>();
                for (File file : Objects.requireNonNull(albumDirectory.listFiles())) {
                    fileList.add(file.toString());
                }
                int maxID = 0;
                long maxLong = 0L;
                String reg = "(?<=" + rootPath + ")\\d{13}(?=\\.jpg)";
                Pattern r = Pattern.compile(reg);
                for (int i = 0; i < fileList.size(); i++) {
                    Matcher matcher = r.matcher(fileList.get(i));
                    while (matcher.find()) {
                        if (Long.parseLong(matcher.group()) > maxLong) {
                            maxID = i;
                            maxLong = Long.parseLong(matcher.group());
                        }
                    }
                }
                //  文件夹内可能无文件导致读取第一张报错
                if (fileList.size() != 0) {
                    String showImage = fileList.get(maxID);
                    final Bitmap bitmap = GetBitmap.getBitmap(showImage);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            albumImage.setImageBitmap(BitmapUtil.bitmapToCircle(Objects.requireNonNull(BitmapUtil.bitmapToSquare(bitmap,
                                    bitmap.getWidth() - 1)), 2));
                        }
                    });
                }
            } else {
                Toast.makeText(SunCameraActivity.this, "图片读取，路径无法创建", Toast.LENGTH_LONG).show();
            }
        }
    }

    //初始化TextureView
    public void initTextureView() {
        texturePreview.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
                //say("textureWidth : "+width+"\ttextureHeight : "+height);
                optimalSize = getOptimalSize(textureWidth, textureHeight);
                textureWidth = width;
                textureHeight = height;
                surfaceTexture = surface;
                surfaceTexture.setDefaultBufferSize(optimalSize.getHeight(),optimalSize.getWidth());
                previewSurface = new Surface(surfaceTexture);
                //  初始化imageReader
                imageReader = ImageReader.newInstance(optimalSize.getWidth(), optimalSize.getHeight(), ImageFormat.JPEG, 2);
                imageReader.setOnImageAvailableListener(imageReaderListener, mBackgroundHandler);
                //say("添加texture监听，可用回调计算得到最佳尺寸：" + optimalSize.getWidth() + "*" + optimalSize.getHeight() + "  初始化preview和imageReader");
                mBackgroundHandler.post(new OpenCameraThread());

            }

            @Override
            public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {

            }

            @Override
            public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {

                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {
            }
        });
    }

    //获取当前Characteristic支持的Size
    public Size getOptimalSize(int textureWidth, int textureHeight) {
        StreamConfigurationMap configurationMap = //一份详细的配置表
                cameraCharacteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        Size[] sizeList = configurationMap.getOutputSizes(SurfaceTexture.class); //提供一个可输出Size的类
        List<Size> readyList = new ArrayList<>();
//            先找尺寸接近的，再找其中分辨率最高的
        float bestRatio = (float) textureHeight / textureWidth;
        int maxSize = 0;
        for (Size size : sizeList) {
            if (Math.abs(((float) size.getWidth() / size.getHeight() - bestRatio)) < 0.3) {
                readyList.add(size);
            }
        }
        for (Size size : readyList) {
            if (size.getWidth() > maxSize) {
                maxSize = size.getWidth();
                sizeList[0] = size;
            }
        }
        return sizeList[0];

    }

    //开启相机线程
    public class OpenCameraThread implements Runnable {

        @Override
        public void run() {
            openCamera();
        }

        //    相机开启
        @SuppressLint("MissingPermission")
        private void openCamera() {
            try {
                cameraManager.openCamera(cameraId, new CameraDevice.StateCallback() {
                    @Override
                    public void onOpened(@NonNull CameraDevice camera) {
                        cameraDevice = camera;
                        //say("开启" + (cameraId.equals("0") ? "后置摄像头" : "前置摄像头") + ",初始化Device，开始会话创建线程");
                        new CreatePreviewSessionThread().run();
                    }

                    @Override
                    public void onDisconnected(@NonNull CameraDevice camera) {
                        cameraDevice = camera;
                        cameraDevice = null;
                    }

                    @Override
                    public void onError(@NonNull CameraDevice camera, int error) {
                        cameraDevice = camera;
                        cameraDevice = null;
                    }
                }, mBackgroundHandler);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }

        }
    }

    //创建预览回调
    {
        previewCallBack = new CameraCaptureSession.CaptureCallback() {
            public void process(CaptureResult result) {
                Integer mode = result.get(CaptureResult.STATISTICS_FACE_DETECT_MODE);
                Face[] faces = result.get(CaptureResult.STATISTICS_FACES);
                if (mode != 0 && faces.length != 0) {
                    handleFaces(faces);
                } else if (faces.length == 0) {
                    faceList.clear();
                    faceView.addFaces(faceList);
                }
                faceCount = faces.length;
            }

            public void handleFaces(Face[] faces) {
                faceList.clear();
                for (Face face : faces) {
                    Rect bounds = face.getBounds();
                    int left = bounds.left;
                    int top = bounds.top;
                    int right = bounds.right;
                    int bottom = bounds.bottom;

                    Rect rect = cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);

                    float bottomRate = (float) bottom / rect.bottom; //成像区底部占比
                    float leftRate = (float) left / rect.right; //成像区左部占比
                    float rightRate = (float) right / rect.right; //成像区右部占比
                    float topRate = (float) top / rect.bottom; //成像区顶部占比

                    int textureRight = (int) ((1 - bottomRate) * textureWidth);
                    int textureTop = (int) ((leftRate) * textureHeight);
                    int textureBottom = (int) ((rightRate) * textureHeight);
                    int textureLeft = (int) ((1 - topRate) * textureWidth);

                    if (cameraId.equals("1")) {
                        textureTop = textureHeight - textureTop;
                        textureBottom = textureHeight - textureBottom;
                    }
                    faceList.add(new RectF(textureLeft, textureTop, textureRight, textureBottom));
                }
                faceView.addFaces(faceList);
            }
            @Override
            public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) {
                super.onCaptureStarted(session, request, timestamp, frameNumber);
            }

            @Override
            public void onCaptureProgressed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureResult partialResult) {
                super.onCaptureProgressed(session, request, partialResult);
            }

            @Override
            public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
                process(result);
                super.onCaptureCompleted(session, request, result);
            }
        };
    }

    //创建预览
    public class CreatePreviewSessionThread implements Runnable {

        @Override
        public void run() {
            if (previewBuilder == null) {
                initPreview();
            }
            if (previewSession != null) {
                clearPreviewSession();
            }
            createPreviewSession();
        }

        //    创建预览会话
        private void createPreviewSession() {
            try {
                // 创建循环请求
                if (cameraDevice != null) {
                    cameraDevice.createCaptureSession(Arrays.asList(previewSurface, imageReader.getSurface()), new CameraCaptureSession.StateCallback() {
                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession session) {
                            previewSession = session;
                            try {
                                previewSession.setRepeatingRequest(previewBuilder.build(),null, mBackgroundHandler);
                                //rotateButton.setClickable(true);
                                Log.e("TAG","预览开启成功");
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onConfigureFailed(@NonNull CameraCaptureSession session) {

                        }
                    }, mBackgroundHandler);
                } else say("cameraDevice 为空,无法创建captureSession");

            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }

        public void initPreview() {
            try {
                previewBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
            previewBuilder.addTarget(previewSurface);
            // 自动对焦
            previewBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            // 闪光灯
            previewBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
            // 根据摄像头方向对保存的照片进行旋转，使其为"自然方向"
            Integer mCameraSensorOrientation = cameraCharacteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
            previewBuilder.set(CaptureRequest.JPEG_ORIENTATION, mCameraSensorOrientation);
            // 人脸检测模式
            previewBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE, CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_SIMPLE);
            //获取成像区域
            Rect cRect = cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
            //支持的最大检测人脸数量
            cPixelSize = cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE);

            //可用于判断是否支持人脸检测，以及支持到哪种程度
            faceDetectModes = cameraCharacteristics.get(CameraCharacteristics.STATISTICS_INFO_AVAILABLE_FACE_DETECT_MODES);//支持的人脸检测模式
            int maxFaceCount = cameraCharacteristics.get(CameraCharacteristics.STATISTICS_INFO_MAX_FACE_COUNT);//支持的最大检测人脸数量

            //previewBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE,getFaceDetectMode());

        }
    }

    //拍照
    public void takePhoto() {
        oldTimer = 0L;
        say("点击拍照完成");
        //takePhotoButton.setClickable(false);
        dark_screen.setVisibility(View.VISIBLE);  //拍照时黑屏一秒
        MediaPlayer.create(this, R.raw.captrue).start();
        mBackgroundHandler.post(new CreateCaptureSessionThread());
    }

    //创建拍照会话
    public class CreateCaptureSessionThread implements Runnable {

        @Override
        public void run() {
            if (captureBuilder == null) {
                initCapture();
            }
            if (mZoomValue != 0L) {
                say("zoomed");
                captureBuilder.set(CaptureRequest.SCALER_CROP_REGION, newRect);
            }
            createCaptureSession();
        }

        //    预览转拍照
        private void createCaptureSession() {
            try {
                //  停止预览开始拍照
                previewSession.stopRepeating();
                previewSession.abortCaptures();
                say("预览停止");
                previewSession.capture(captureBuilder.build(), new CameraCaptureSession.CaptureCallback() {
                    @Override
                    public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
                        super.onCaptureCompleted(session, request, result);
                        try {
                            previewSession.setRepeatingRequest(previewBuilder.build(), previewCallBack, mBackgroundHandler);
                           // takePhotoButton.setClickable(true);
                            if (captureImage != null) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        dark_screen.setVisibility(View.GONE);
                                    }
                                });
                                mBackgroundHandler.post(new SaveImage());
                            }
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        }
                        //SunCameraActivity.this.onCameraImagePreviewed(result);
                    }
                }, mBackgroundHandler);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }

        //    初始化拍摄参数
        public void initCapture() {
            try {
                captureBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
            // 自动对焦
            captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            // 闪光灯
            captureBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
            // 根据摄像头方向对保存的照片进行旋转，使其为"自然方向"
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, 90);
            // 人脸检测模式
            captureBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE, CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_SIMPLE);

            captureBuilder.addTarget(previewSurface);
            captureBuilder.addTarget(imageReader.getSurface());
            say("初始化完成拍照参数");
        }
    }

    //延时拍照
    private void takeDelayShot() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (delayTime > 0) {
                    delayNumber.setText(String.valueOf(delayTime));
                    delayNumber.setVisibility(View.VISIBLE);
                    delayTime--;
                    mBackgroundHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            takeDelayShot();
                        }
                    }, 1000);
                } else if (delayTime == 0) {
                    delayNumber.setVisibility(View.GONE);
                    takePhoto();
                    delayTime = share.getInt("delayTime", 0);
                } else if (delayTime == -1) {
                    delayNumber.setVisibility(View.GONE);
                    delayTime = share.getInt("delayTime", 0);
                }
            }
        });
    }

    //初始化mediaRecorder
    public void initMediaRecorder() {
        File videoRootPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM),
                "MediaRecorderStorage");
        if (!videoRootPath.exists() && !videoRootPath.mkdir()) {
            say("根目录:videoRootPath(" + videoRootPath.toString() + ")创建失败");
        } else {
            videoFile = new File(videoRootPath, "video" + System.currentTimeMillis() + ".mp4");
            say("输出文件(" + videoFile);
        }
        clearPreviewSession();
        recorder = new MediaRecorder();
        say("新建recorder");
        //    这两项需要放在setOutputFormat之前
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        say("看看尺寸差别： width :" + textureWidth + " height :" + textureHeight + " optimal :" + optimalSize.toString());
        recorder.setVideoSize(optimalSize.getWidth(), optimalSize.getHeight());
        recorder.setVideoEncodingBitRate(10000000);
        recorder.setVideoFrameRate(30);
        if (cameraId.equals("0")) {
            recorder.setOrientationHint(90);
        } else {
            recorder.setOrientationHint(270);
        }
        recorder.setPreviewDisplay(previewSurface);
        recorder.setMaxDuration(30 * 1000);
        recorder.setOutputFile(videoFile.getAbsolutePath());
        say("参数设置完成");
        try {
            recorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        say("recorder就绪");
        mediaRecorderSurface = recorder.getSurface();
        say("获取到mediaSurface");

        try {
            previewBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_VIDEO);
            previewBuilder.addTarget(previewSurface);
            previewBuilder.addTarget(mediaRecorderSurface);
            cameraDevice.createCaptureSession(Arrays.asList(previewSurface, mediaRecorderSurface), new CameraCaptureSession.StateCallback() {
                @Override
                public void onConfigured(@NonNull CameraCaptureSession session) {
                    previewSession = session;
                    try {
                        previewSession.setRepeatingRequest(previewBuilder.build(), null, mBackgroundHandler);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onConfigureFailed(@NonNull CameraCaptureSession session) {

                }
            }, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
        say("录像模式预览完成");
    }

    //录像
    public void takeVideo() {
        //            开始录制转停止录制
        if (isRecording) {
            recorder.stop();
            recorder.release();
            recorder = null;
            isRecording = false;
            previewBuilder.removeTarget(mediaRecorderSurface);
            //  将preview和mediaSurface作为target开始预览
            new CreatePreviewSessionThread().run();
            bottomConstraint.setAlpha(1);
            chronometer.stop();
            //chronometer.setBase(SystemClock.elapsedRealtime()); //计时器清零

            say("————stop recording————");
        } else {
            //  暂停预览，准备media，初始化，camera再开启一个预览会话
            initMediaRecorder();
            recorder.start();
            isRecording = true;
            bottomConstraint.setAlpha(0.2F);  //开启录像时设置透明度

            chronometer.setBase(SystemClock.elapsedRealtime()); //计时器清零
            //设置计时器格式为00:00:00
            int hour = (int) ((SystemClock.elapsedRealtime() - chronometer.getBase()) /1000 /60);
            chronometer.setFormat("0"+String.valueOf(hour)+":%s");
            chronometer.start();
            chronometer.setVisibility(View.VISIBLE);  //显示定时器
            MedioIcon.setVisibility(View.VISIBLE);   //显示录像图标
            MedioIcon.setBackground(SunCameraActivity.this.getResources().getDrawable(R.drawable.recoder5));

            changeFaceDetectedMod(0);

            say("————start recording————");
        }
       // takePhotoButton.setClickable(true);
    }

    //存储图片
    public class SaveImage implements Runnable {
        @Override
        public void run() {
            say("拿到图片");
            ByteBuffer buffer = captureImage.getPlanes()[0].getBuffer();
            byte[] data = new byte[buffer.remaining()];
            buffer.get(data);
            say("数据转入byte数组");
            captureImage.close();
            captureImage = null;
            say("关闭并清空image");
            Bitmap bitmap = BitmapUtil.rotateBitmapByDegree(
                    BitmapFactory.decodeByteArray(data, 0, data.length),
                    (cameraId.equals("0") ? 90 : 270));
            say("byte数组转bitmap同时旋转到正常角度");
            try {
                File finalPath = new File(rootPath, System.currentTimeMillis() + ".jpg");
                FileOutputStream fos = new FileOutputStream(finalPath);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                say("将bitmap压缩到输出文件");
                fos.flush();
                fos.close();
                say("关闭输出流");
                notifyUpdate(new File(String.valueOf(finalPath)));
                mBackgroundHandler.post(new GetLatestAlbum());
                say("通知图库完成");
                Log.e("TAG","finalPath++++++"+finalPath);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    //通知图库更新
    public void notifyUpdate(File file) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) { //要求sdk大于25 android7.0及以上 储存方式发生了改变
            MediaScannerConnection.scanFile(this, new String[]{file.getAbsolutePath()}, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        @Override
                        public void onScanCompleted(String path, Uri uri) {
                            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                            mediaScanIntent.setData(uri);
                            sendBroadcast(mediaScanIntent); //扫描完毕，发送广播通知图库更新
                        }
                    });
        } else {
            say("设备的版本低于Android7.0");
            String relationDir = file.getParent();
            assert relationDir != null;
            File file1 = new File(relationDir);
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(file1.getAbsoluteFile())));
        }

    }

    //旋转摄像头
    public void rotateCamera() {
       // rotateButton.setClickable(false);
        previewSession.close();
        previewSession = null;
        cameraDevice.close();
        cameraDevice = null;
        if (cameraId.equals("0")) {
            initCameraManager("1");
        } else initCameraManager("0");
        mBackgroundHandler.post(new OpenCameraThread());
    }

    //手动聚焦画框
    public class Focus implements Runnable {

        private Point point;
        private ConstraintSet applyConstrainSet = new ConstraintSet();
        private ConstraintLayout constraintLayout = findViewById(R.id.constraint_preview);
        private Animation animation;

        public Focus(Point point) {
            this.point = point;
        }

        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    animation = AnimationUtils.loadAnimation(SunCameraActivity.this, R.anim.anim_scale);
                    image_focus.startAnimation(animation);
                    image_focus.setVisibility(View.VISIBLE);
                    applyConstrainSet.clone(constraintLayout);
                    applyConstrainSet.setMargin(image_focus.getId(), ConstraintSet.LEFT, point.x - (image_focus.getWidth() / 2));
                    applyConstrainSet.setMargin(image_focus.getId(), ConstraintSet.TOP, point.y - (image_focus.getHeight() / 2));
                    applyConstrainSet.applyTo(constraintLayout);

                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            image_focus.setVisibility(View.GONE);
                        }
                    }, 1000);
                }
            });
        }
    }

    //触发手动对焦
    public void startControlAFRequest(MeteringRectangle rect) {

        MeteringRectangle[] rectangle = new MeteringRectangle[]{rect};
        // 对焦模式必须设置为AUTO
        previewBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_AUTO);
        //AE
        previewBuilder.set(CaptureRequest.CONTROL_AE_REGIONS, rectangle);
        //AF 此处AF和AE用的同一个rect, 实际AE矩形面积比AF稍大, 这样测光效果更好
        previewBuilder.set(CaptureRequest.CONTROL_AF_REGIONS, rectangle);
        //设置人脸识别
        previewBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE, CameraCharacteristics.STATISTICS_FACE_DETECT_MODE_SIMPLE);
        try {
            // AE/AF区域设置通过setRepeatingRequest不断发请求
            previewSession.setRepeatingRequest(previewBuilder.build(), previewCallBack, mBackgroundHandler);
            //触发对焦
            previewBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CaptureRequest.CONTROL_AF_TRIGGER_START);
            //触发对焦通过capture发送请求, 因为用户点击屏幕后只需触发一次对焦
            previewSession.capture(previewBuilder.build(), null, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    //触摸点换算成底层坐标
    public MeteringRectangle calcTapAreaForCamera2(CameraCharacteristics c, int currentX, int currentY, int areaSize, int weight) {
        // 获取Size
        Rect rect = c.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
        int leftPos, topPos;
        // 坐标转换
        float newX = currentY;
        float newY = textureWidth - currentX;
        // 大小转换
        leftPos = (int) ((newX / textureHeight) * rect.right);
        topPos = (int) ((newY / textureHeight) * rect.bottom);
        // 以坐标点为中心生成一个矩形, 需要防止上下左右的值溢出
        int left = clamp(leftPos - areaSize, 0, rect.right);
        int top = clamp(topPos - areaSize, 0, rect.bottom);
        int right = clamp(leftPos + areaSize, leftPos, rect.right);
        int bottom = clamp(topPos + areaSize, topPos, rect.bottom);
        newRect = new Rect(left, top, right, bottom);
        // 构造MeteringRectangle
        return new MeteringRectangle(newRect, weight);
    }

    //触摸边界计算
    public int clamp(int x, int min, int max) {
        if (x > max) {
            return max;
        }
        if (x < min) {
            return min;
        }
        return x;
    }

    //计算两个触摸点之间的距离
    public float distance(MotionEvent event) {
        float x = 0;
        float y = 0;
        try {
            x = event.getX(0) - event.getX(1);
            y = event.getY(0) - event.getY(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (float) Math.sqrt(x * x + y * y);
    }

    //清空session
    public void clearPreviewSession() {
        try {
            previewSession.stopRepeating();
            previewSession.close();
            previewSession = null;
            Log.e("TAG","清空previewSession");
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    //页面状态栏最顶部为黑色
    private void setWindowFlag() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        WindowManager.LayoutParams params = window.getAttributes();
        params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE;
        window.setAttributes(params);
    }

    //打印
    public void say(String word) {
        if (oldTimer == 0L) {
            oldTimer = System.currentTimeMillis();
            LogUtil.log("开始计时\t" + word);
        } else {
            nowTimer = System.currentTimeMillis();
            long dist = nowTimer - oldTimer;
            if (dist < 5000L) {
                LogUtil.log(("耗时：" + (dist) + "\t\t") + word);
                oldTimer = nowTimer;
            } else {
                LogUtil.log("超时：" + (dist) + "\t\t" + word);
                oldTimer = 0L;
            }
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                Toast.makeText(this, "再按一次退出程序", (int) 2000).show();
                firstTime = secondTime;
                return true;
            } else {
                finish();
                System.exit(0);
            }
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        if (previewBuilder != null) {
            mBackgroundHandler.post(new OpenCameraThread());
        }
        super.onResume();
    }

    @Override
    protected void onStop() {
        if (previewSession != null) {
            say("previewSession不为空，关闭其清空对应session和device，在Resume重新启动openCamera线程");
            previewSession.close();
            previewSession = null;
            cameraDevice.close();
            cameraDevice = null;
        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    //修改缩放参数
    public void applyZoom(float zoom) {
        mZoomValue = zoom;
        if (cameraCharacteristics != null) {
            float maxZoom = cameraCharacteristics.get(
                    CameraCharacteristics.SCALER_AVAILABLE_MAX_DIGITAL_ZOOM);
            //  1.55555 * 10 15.5555 round 16 / 10 float 1.6
            float realZoom = (float) Math.round(((mZoomValue * (maxZoom - 1.0f)) + 1.0f) * 10) / 10;
            zoomNumber.setText(String.valueOf(realZoom));
            newRect = getZoomRect(realZoom, maxZoom);
            previewBuilder.set(CaptureRequest.SCALER_CROP_REGION, newRect);
            previewBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);
            try {
                previewSession.setRepeatingRequest(previewBuilder.build(), null, mBackgroundHandler);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }
    }

    //获取缩放截取范围
    public Rect getZoomRect(float zoomLevel, float maxDigitalZoom) {
        Rect activeRect;

        activeRect = cameraCharacteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);

        int minW = (int) (activeRect.width() / maxDigitalZoom); // 单位缩放等级所占的宽高
        int minH = (int) (activeRect.height() / maxDigitalZoom);
        int difW = activeRect.width() - minW;
        int difH = activeRect.height() - minH;

        // When zoom is 1, we want to return new Rect(0, 0, width, height).
        // When zoom is maxZoom, we want to return a centered rect with minW and minH
        int cropW = (int) (difW * (zoomLevel - 1) / (maxDigitalZoom - 1) / 2f); // 缩放等级越大Rect越往中间靠 除数延缓缩放速度
        int cropH = (int) (difH * (zoomLevel - 1) / (maxDigitalZoom - 1) / 2f);
        return new Rect(cropW, cropH, activeRect.width() - cropW,
                activeRect.height() - cropH);
    }


    //处理相机画面处理完成事件，获取检测到的人脸坐标，换算并绘制人脸方框
  /*  private void onCameraImagePreviewed(CaptureResult result){
        Face faces[]=result.get(CaptureResult.STATISTICS_FACES);

        Canvas canvas = faceView.lockCanvas();
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);//旧画面清理覆盖

        if(faces.length>0){
            for(int i=0;i<faces.length;i++){
                Rect fRect = faces[i].getBounds();

                //人脸检测坐标基于相机成像画面尺寸以及坐标原点。此处进行比例换算
                //成像画面与方框绘制画布长宽比比例（同画面角度情况下的长宽比例（此处前后摄像头成像画面相对预览画面倒置（±90°），计算比例时长宽互换））
                float scaleWidth = canvas.getHeight()*1.0f/cPixelSize.getWidth();
                float scaleHeight = canvas.getWidth()*1.0f/cPixelSize.getHeight();

                //坐标缩放
                int l = (int) (fRect.left*scaleWidth);
                int t = (int) (fRect.top*scaleHeight);
                int r = (int) (fRect.right*scaleWidth);
                int b = (int) (fRect.bottom*scaleHeight);

                // Log.e("TAG","[T"+i+"]:[left:"+l+",top:"+t+",right:"+r+",bottom:"+b+"]");
                //人脸检测坐标基于相机成像画面尺寸以及坐标原点。此处进行坐标转换以及原点(0,0)换算
                //人脸检测：坐标原点为相机成像画面的左上角，left、top、bottom、right以成像画面左上下右为基准
                //画面旋转后：原点位置不一样，根据相机成像画面的旋转角度需要换算到画布的左上角，left、top、bottom、right基准也与原先不一样，
                //如相对预览画面相机成像画面角度为90°那么成像画面坐标的top，在预览画面就为left。如果再翻转，那成像画面的top就为预览画面的right，且坐标起点为右，需要换算到左边
                *//*if(isFront){
                    //此处前置摄像头成像画面相对于预览画面顺时针90°+翻转。left、top、bottom、right变为bottom、right、top、left，并且由于坐标原点由左上角变为右下角，X,Y方向都要进行坐标换算
                    canvas.drawRect(canvas.getWidth()-b,canvas.getHeight()-r,canvas.getWidth()-t,canvas.getHeight()-l,getPaint());
                }else{
                    //此处后置摄像头成像画面相对于预览画面顺时针270°，left、top、bottom、right变为bottom、left、top、right，并且由于坐标原点由左上角变为左下角，Y方向需要进行坐标换算

                }*//*
                canvas.drawRect(canvas.getWidth()-b,l,canvas.getWidth()-t,r,getPaint());
            }
        }
        faceView.unlockCanvasAndPost(canvas);
    }

    //初始化画笔
    private Paint pb;
    private Paint getPaint(){
        if(pb == null){
            pb =new Paint();
            pb.setColor(Color.WHITE);
            pb.setStrokeWidth(10f);
            pb.setStyle(Paint.Style.STROKE);//使绘制的矩形中空
        }
        return pb;
    }

    //获取支持的最高人脸检测级别
    private int getFaceDetectMode(){
        if(faceDetectModes == null){
            return CaptureRequest.STATISTICS_FACE_DETECT_MODE_FULL;
        }else{
            return faceDetectModes[faceDetectModes.length-1];
        }
    }
*/

    //拍照声音
    private void photo_voice(){
        audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        mediaPlayer = MediaPlayer.create(this,R.raw.shut);
        //mediaPlayer.setLooping(true); //循环播放声音
        mediaPlayer.start();
    }

    //录像声音
    private void video_voice(){
        audioManager = (AudioManager) getSystemService(Service.AUDIO_SERVICE);
        mediaPlayer = MediaPlayer.create(this,R.raw.recoder);
        mediaPlayer.start();
    }

    //延时模式
    public void changeDelayMode(int time) {
        if (time != 0) {
            textView_delay.setText(time + "秒延时");
        } else {
            textView_delay.setText("无延时");
        }
        ((SunCameraActivity) Objects.requireNonNull(this)).activeDelayMode(time);
    }

    //人脸检测开关
    public void changeFaceDetectedMode(int faceMode) {
        if (faceMode == 1) {
            textView_face.setText("开启");
        } else if (faceMode == 0) {
            textView_face.setText("关闭");
        }
        LogUtil.log("修改faceMode ：" + faceMode);
        ((SunCameraActivity) Objects.requireNonNull(this)).changeFaceDetectedMod(faceMode);
    }

    //人脸检测模式
    public void changeFaceDetectedMod(int detectedMod) {
        try {
            if (detectedMod == 1) {
                // 人脸检测模式
                previewBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE, CaptureRequest.STATISTICS_FACE_DETECT_MODE_SIMPLE);
            } else if (detectedMod == 0) {
                previewBuilder.set(CaptureRequest.STATISTICS_FACE_DETECT_MODE, CaptureRequest.STATISTICS_FACE_DETECT_MODE_OFF);
            }
            previewSession.setRepeatingRequest(previewBuilder.build(), previewCallBack, mBackgroundHandler);
            SharedPreferences.Editor edit = share.edit();
            edit.putInt("faceMode", detectedMod);
            edit.apply();
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    //循环人脸数量显示
    public void showFaceNumber() {
        if (faceCount != 0) {
            Toast.makeText(SunCameraActivity.this, "人脸数：" + faceCount, (int) 800).show();
        }
        mBackgroundHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                showFaceNumber();
            }
        }, 1000);
    }

}
